<template>
  <view class="container">
    <!-- 头部区域 -->
    <view class="header">
      <view class="user-info">
        <image :src="loginUser.avatarUrl || '/static/profile/defaultAvatar.png'" class="avatar" />
        <view class="user-detail">
          <text class="username" v-if="token">{{ loginUser.userName || '默认用户' }}</text>
          <text class="user-phone" v-if="token && loginUser.phone">{{ formatPhone(loginUser.phone) }}</text>
          <button class="login-btn" v-if="!token" @click="goToLogin">
            <text class="btn-text">一键登录</text>
            <text class="btn-icon">></text>
          </button>
        </view>
      </view>
      <view class="header-bg"></view>
    </view>

    <!-- 订单状态区域 -->
    <view class="order-section">
      <view class="section-title">
        <text>我的订单</text>
        <view class="view-all" @click="goToOrderStatus('全部')">
          <text>查看全部</text>
          <text class="arrow">></text>
        </view>
      </view>
      <view class="order-icons">
        <view class="order-icon" @click="goToOrderStatus('待付款')">
          <image src="/static/profile/daifukuan.png" class="icon" />
          <text>待付款</text>
        </view>
        <view class="order-icon" @click="goToOrderStatus('待发货')">
          <image src="/static/profile/daifahuo.png" class="icon" />
          <text>待发货</text>
        </view>
        <view class="order-icon" @click="goToOrderStatus('已发货')">
          <image src="/static/profile/yifahuo.png" class="icon" />
          <text>已发货</text>
        </view>
        <view class="order-icon" @click="goToOrderStatus('交易完成')">
          <image src="/static/profile/jiaoyiwancheng.png" class="icon" />
          <text>交易完成</text>
        </view>
        <view class="order-icon" @click="goToOrderStatus('交易关闭')">
          <image src="/static/profile/jiaoyiguanbi.png" class="icon" />
          <text>售后/退款</text>
        </view>
      </view>
    </view>

    <!-- 功能区域 -->
    <view class="function-section">
      <view class="section-title">
        <text>我的服务</text>
      </view>
      <view class="function-list">
        <view class="function-item" @click="goToBalance">
          <image src="/static/profile/wodedingdan.png" class="icon" />
          <text>我的订单</text>
        </view>
        <view class="divider"></view>
        <view class="function-item" @click="goToCoupon">
          <image src="/static/coupon.png" class="icon" />
          <text>我的优惠券</text>
        </view>
        <view class="divider"></view>
        <view class="function-item" @click="goToAddress">
          <image src="/static/profile/address.png" class="icon" />
          <text>收货地址</text>
        </view>
        <view class="divider"></view>
        <view class="function-item" @click="goToCustomerService">
          <image src="/static/profile/客服.png" class="icon" />
          <text>联系客服</text>
        </view>
        <view class="divider"></view>
        <view v-if="token" class="function-item" @click="goToSetting">
          <image src="/static/profile/设置.png" class="icon" />
          <text>设置</text>
        </view>
        <view class="divider"></view>
        <view class="function-item" v-if="token"  @click="logout">
          <image src="/static/profile/logout.png" class="icon" />
          <text>退出登录</text>
        </view>
        <view class="function-item" v-if="!token"  @click="toLoginPage">
          <image src="/static/profile/psw_login.png" class="icon" />
          <text>密码登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import { useLoginUserStore } from '@/store/loginUserStore';
import { tokenStore } from '@/store/tokenStore';
import { userLoginUsingPost, getLoginUserUsingGet } from '@/backend';
import type { API } from '../../backend/typings';
import Log from "@umijs/openapi/dist/log";

const loginStore = useLoginUserStore();
const tokenStoreInstance = tokenStore();

// 格式化手机号
const formatPhone = (phone: string) => {
  if (!phone) return '';
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

const token = ref<string | null>(null);
const loginUser = ref<API.LoginUserVO>({
  userName: undefined,
  phone: undefined,
  avatarUrl: undefined,
  email: undefined,
  id: undefined,
  createTime: undefined,
  updateTime: undefined,
  openid: undefined,
  userRole: undefined
});

// 获取用户信息的函数
const fetchUserInfo = async () => {
  try {
    if (tokenStoreInstance.getToken) {
      const userRes = await getLoginUserUsingGet();
      if (userRes.code === 0 && userRes.data) {
        loginUser.value = userRes.data;
        loginStore.setLoginUser(userRes.data);
        token.value = tokenStoreInstance.getToken;
      }
    }
  } catch (err) {
    console.error('获取用户信息失败：', err);
  }
};

// 页面显示时刷新用户信息
onShow(() => {
  token.value = tokenStoreInstance.getToken;
  fetchUserInfo();
});

// 添加下拉刷新处理
onPullDownRefresh(async () => {
  try {
    await fetchUserInfo();
  } finally {
    uni.stopPullDownRefresh();
  }
});

// onMounted 也调用这个函数
onMounted(() => {
  token.value = tokenStoreInstance.getToken;
  const storedUser = loginStore.getLoginUser;
  if (storedUser) {
    loginUser.value = storedUser;
  }
  fetchUserInfo();

  // 添加事件监听
  uni.$on('updateUserInfo', fetchUserInfo);
});

// 记得在组件卸载时移除监听
onUnmounted(() => {
  uni.$off('updateUserInfo', fetchUserInfo);
});

// onPullDownRefresh(()=>{
//   loginUser.value=loginStore.getLoginUser
// })

// 跳转到订单状态页面
const goToOrderStatus = (status: string) => {
  // 根据状态获取对应的标签页索引
  let tabIndex = 0;
  switch (status) {
    case '全部':
      tabIndex = 0;
      break;
    case '待付款':
      tabIndex = 1;
      break;
    case '待发货':
      tabIndex = 2;
      break;
    case '已发货':
      tabIndex = 3;
      break;
    case '交易完成':
      tabIndex = 4;
      break;
    case '交易关闭':
      tabIndex = 6; // 售后/退款标签页
      break;
    default:
      tabIndex = 0;
  }
  
  uni.navigateTo({
    url: `/pages/orders/orders?tabIndex=${tabIndex}`,
  });
};

// 跳转登录页
const toLoginPage = () => {
  uni.navigateTo({
    url: '/pages/login/login',
  });
};

const goToBalance = () => {
  if (!token.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  uni.navigateTo({
    url: '/pages/orders/orders'
  });
};

const goToCoupon = () => {
  if (!token.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  uni.navigateTo({
    url: '/pages/coupon/coupon'
  });
};

// 跳转到地址管理页面
const goToAddress = () => {
  uni.navigateTo({
    url: '/pages/address/address',
  });
};

// 跳转到设置页面
const goToSetting = () => {
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
    });
    return;
  }
  uni.navigateTo({
    url: '/pages/settings/settings',
  });
};

const goToCustomerService = () => {
  uni.navigateTo({
    url: '/pages/customerService/customerService',
  });
}

// 退出登录
const logout = () => {
  // 使用 tokenStore 的方法清除 token
  tokenStoreInstance.setToken(null);
  token.value = null;
  loginUser.value = {
    userName: undefined,
    phone: undefined,
    avatarUrl: undefined,
    email: undefined,
    id: undefined,
    createTime: undefined,
    updateTime: undefined,
    openid: undefined,
    userRole: undefined
  };
  loginStore.setLoginUser(null); // 同时清除登录用户信息
  uni.showToast({
    title: '已退出登录',
    icon: 'success',
  });
};

// 处理手机号登录
/*
const handlePhoneNumber = async (e: any) => {
  try {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      console.error('获取手机号失败:', e.detail.errMsg);
      return;
    }

    const loginRes = await uni.login();
    const { code } = loginRes;

    const phoneData = {
      code,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
    };

    const phoneResponse = await userLoginUsingPost(phoneData);
    if (phoneResponse.code !== 0) {
      throw new Error(phoneResponse.message);
    }

    // 保存token
    tokenStoreInstance.setToken(phoneResponse.data || null);

    // 获取用户信息
    const userRes = await getLoginUserUsingGet();

    // 更新用户信息
    // @ts-ignore
    loginUser.value = userRes.data || {
      userName: null,
      phone: null,
      avatarUrl: null,
      email: null
    };
    loginStore.setLoginUser(loginUser.value);
    token.value = tokenStoreInstance.getToken || null;

    uni.showToast({
      title: '登录成功',
      icon: 'success'
    });
  } catch (err) {
    console.error('手机号登录失败：', err);
    uni.showToast({
      title: '登录失败',
      icon: 'error'
    });
  }
};
*/

// 授权登录
const goToLogin = async () => {
  try {
    const loginRes = await uni.login();
    const {code} = loginRes;
    const phoneResponse = await userLoginUsingPost(
        {
          code: code,
        }
    );
    if (phoneResponse.code !== 0) {
      throw new Error(phoneResponse.message);
    }
    // 保存token
    tokenStoreInstance.setToken(phoneResponse.data || null);

    // 获取用户信息
    const userRes = await getLoginUserUsingGet();

    // 更新用户信息
    // @ts-ignore
    loginUser.value = userRes.data || {
      userName: null,
      phone: null,
      avatarUrl: null,
      email: null
    };
    loginStore.setLoginUser(loginUser.value);
    token.value = tokenStoreInstance.getToken || null;

    uni.showToast({
      title: '登录成功',
      icon: 'success'
    });
  } catch (err) {
    console.error('登录失败：', err);
    uni.showToast({
      title: '登录失败',
      icon: 'error'
    });
  }

};

</script>

<style scoped>
.container {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  background: linear-gradient(135deg, #ff9800, #ff5722);
  padding: 40rpx 32rpx;
  border-radius: 0 0 40rpx 40rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(255, 87, 34, 0.2);
  position: relative;
  overflow: hidden;
}

.header-bg {
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.user-info {
  display: flex;
  align-items: center;
  position: relative;
  z-index: 1;
}

.avatar {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
  transition: transform 0.3s ease;
}

.avatar:active {
  transform: scale(0.95);
}

.user-detail {
  margin-left: 32rpx;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.username {
  font-size: 40rpx;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.user-phone {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

.login-btn {
  background: rgba(255, 255, 255, 0.95);
  color: #ff5722;
  font-size: 28rpx;
  padding: 16rpx 40rpx;
  border-radius: 48rpx;
  border: none;
  box-shadow: 0 8rpx 16rpx rgba(255, 87, 34, 0.2);
  display: flex;
  align-items: center;
  gap: 8rpx;
  transition: transform 0.2s ease;
}

.login-btn:active {
  transform: scale(0.95);
  box-shadow: 0 4rpx 8rpx rgba(255, 87, 34, 0.2);
}

.btn-text {
  font-weight: 500;
}

.btn-icon {
  font-size: 24rpx;
  opacity: 0.8;
}

.order-section, .function-section {
  background-color: #fff;
  margin: 24rpx 24rpx;
  padding: 32rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title text {
  font-size: 17px;
  font-weight: 600;
  color: #333;
}

.view-all {
  display: flex;
  align-items: center;
  gap: 4rpx;
}

.arrow {
  font-size: 24rpx;
  color: #999;
  transition: transform 0.2s ease;
}

.view-all:active .arrow {
  transform: translateX(4rpx);
}

.order-icons {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
}

.order-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: transform 0.2s;
}

.order-icon:active {
  transform: scale(0.95);
}

.order-icon .icon {
  width: 32px;
  height: 32px;
  margin-bottom: 8px;
}

.order-icon text {
  font-size: 13px;
  color: #666;
}

/* 功能区域样式优化 */
.function-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  transition: background-color 0.2s;
}

.function-item:active {
  background-color: #f5f5f5;
}

.function-item .icon {
  width: 26px;
  height: 26px;
  margin-right: 16px;
}

.function-item text {
  font-size: 15px;
  color: #333;
}

.divider {
  height: 1px;
  background-color: #f0f0f0;
  margin: 0;
}
</style>
